package com.quickcode.example.lock;

import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionExample1 {

    public static final ReentrantLock LOCK = new ReentrantLock();

    public static final Condition CONDITION_EMPT = LOCK.newCondition();

    public static final Condition CONDITION_FULL = LOCK.newCondition();

    public static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(20,100,60, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(500));

    public static void main(String[] args) {
        Queue<String> queue = new ConcurrentLinkedQueue<>();

        EXECUTOR_SERVICE.execute(() -> {
            int i = 0;
            while (true) {
                try {
                    LOCK.lock();
                    CONDITION_EMPT.signal();
                    if(queue.size() == 10) {
                        try {
                            CONDITION_FULL.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.offer("size:" + queue.size());
                } finally {
                    LOCK.unlock();
                }

            }
        });

        EXECUTOR_SERVICE.execute(() -> {
            int i = 0;
            while (true) {
                try {
                    LOCK.lock();
                    CONDITION_FULL.signal();
                    if(queue.size() == 0) {
                        try {
                            CONDITION_EMPT.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(queue.poll());
                } finally {
                    LOCK.unlock();
                }

            }
        });


        while (true) {

        }
    }

}